package de.schule.barnimgymnasium.autotransporter;

import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;

public class GameItem {

	protected final Composite parent;
	protected Image img = null;
	protected Point location;
	private Point mouseDown = null;
	private Point moveLocation = null;

	public GameItem(final Composite parent, final int x, final int y) {
		this.parent = parent;
		this.location = new Point(x, y);
	}

	public void setImage(final Image img) {
		this.img = img;
	}

	public void paintControl(final PaintEvent e) {
		if (img != null) {
			e.gc.drawImage(img, location.x, location.y - img.getBounds().height);
		}
	}

	public boolean mouseDoubleClick(final MouseEvent e) {
		return true;
	}

	public boolean mouseDown(final MouseEvent e) {
		if (!isInsideImage(e.x, e.y, true)) {
			return false;
		}
		mouseDown = new Point(e.x, e.y);
		moveLocation = new Point(location.x, location.y);
		return true;
	}

	public boolean mouseUp(final MouseEvent e) {
		if (mouseDown == null) {
			return false;
		}
		mouseDown = null;
		return true;
	}

	public boolean mouseMove(final MouseEvent e) {
		if (mouseDown == null) {
			return false;
		}
		this.moveLocation(moveLocation.x + e.x - mouseDown.x, moveLocation.y
				+ e.y - mouseDown.y);
		return true;

	}

	private boolean isInsideImage(final int x, final int y,
			final boolean onlyVisiblePixel) {
		if (img == null) {
			return false;
		}
		final int relativeX = x - this.location.x;
		if (relativeX < 0) {
			return false;
		}
		if (relativeX >= img.getBounds().width) {
			return false;
		}
		final int relativeY = y - this.location.y + img.getBounds().height;
		if (relativeY < 0) {
			return false;
		}
		if (relativeY >= img.getBounds().height) {
			return false;
		}
		if (!onlyVisiblePixel) {
			return true;
		}
		final int index = relativeY * img.getBounds().width + relativeX;
		if (img.getImageData().alphaData[index] == -1) {
			return true;
		}
		return false;
	}

	public Point getLocation() {
		return this.location;
	}

	public void setLocation(final Point newLocation) {
		location = newLocation;
	}

	public boolean isItemInsideParentArea(final int x, final int y) {
		final Rectangle area = parent.getClientArea();
		// System.out.println(area + ", X:" + x + ", Y:" + y);
		if (area.contains(x, y)) {
			if (img == null) {
				return true;
			} else {
				return area.contains(x + img.getBounds().width,
						y - img.getBounds().height);
			}
		} else {
			return false;
		}
	}

	public void moveLocation(final int x, final int y) {
		if (this.isItemInsideParentArea(x, y)) {
			this.location.x = x;
			this.location.y = y;
		}
	}

	public void movetoSnap(final Point newLocation) {
		this.moveLocation(newLocation.x, newLocation.y);
	}

}
